<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/26
 * Time: 上午11:27
 * Describe: iliketry order's data export to d_try.
 */

namespace console\models;

use common\models\OrderExpress;
use common\models\OrderGoods;
use common\models\OrderInfo;
use common\models\iliketry\Order;
use services\models\Cart;
use Yii;
use common\helper\ArrayHelper;
use yii\base\Exception;

class LiketryToDTry extends Object
{
    public static $province         = [];
    public static $city             = [];
    public static $area             = [];
    public static $uids             = [];
    public static $D_TRY_ID_BASE    = 40000000;
    public static $ILIKETRY_ID_BASE = 20000000;
    public        $isEnd            = false;
    public        $page_size        = 500;
    public        $begin_id         = 0;
    public        $end_id           = 0;

    public static $city_province  = [];
    public static $STATUS_LIKETRY = [
        "发货中"    => 1
        , "已发货"  => 3
        , "已完成"  => 5
        , "已打包"  => 3
        , "已收货"  => 4
        , "已放弃"  => 6
        , "已申领"  => 0
        , "无效订单" => 6
        , "派发中"  => 3
        , "过期订单" => 6];

    public function init()
    {
        $result = Yii::$app->getDb()->createCommand("select uid, lkt_uid from tmall1.member_info WHERE lkt_uid >0")->queryAll();
        foreach ($result as $item) {
            static::$uids[$item['lkt_uid']] = $item['uid'];
        }
        $result = Yii::$app->getDb()->createCommand("select no, name from iliketry.province")->queryAll();
        foreach ($result as $item) {
            static::$province[$item['no']] = $item['name'];
        }
        $result = Yii::$app->getDb()->createCommand("select no, name, province_no from iliketry.city")->queryAll();
        foreach ($result as $item) {
            static::$city[$item['no']]          = $item['name'];
            static::$city_province[$item['no']] = $item['province_no'];
        }
        $result = Yii::$app->getDb()->createCommand("select no,name from iliketry.area_member")->queryAll();
        foreach ($result as $item) {
            static::$area[$item['no']] = $item['name'];
        }
        if ($this->end_id == 0) {
            $this->end_id = static::$ILIKETRY_ID_BASE;
        }

        parent::init();
    }

    public function writeData()
    {
        static::info('导入开始ID:' . $this->begin_id);
        $result = Order::find()->filterWhere(['>', 'no', $this->begin_id])->orderBy(['no' => 'asc'])->limit($this->page_size)->all();

        if (empty($result)) {
            $this->isEnd = true;
            static::info('结束导入从iliketry.order,最后ID：' . $this->begin_id);
            return;
        }
        /** @var Order $item */
        foreach ($result as $item) {
            $this->begin_id = $item->no;

            if ($this->end_id > 0 && $item->no > $this->end_id) {
                $this->isEnd = true;
                return;
            }

            if ($item->status == '已申领' || $item->status == '已打包') {
                #$this->addCart($item);
                continue;
            }

            try {


                $order = new OrderInfo();
                #todo: add bestry_uid
                $bestry_uid           = static::$uids[$item->member_no];
                $order->order_info_id = $item->no + static::$ILIKETRY_ID_BASE;
                $order->order_sn      = $item->order_code;
                $order->bestry_uid    = $bestry_uid;
                $order->type          = 1;
                $order->create_time   = date('Y-m-d H:i:s', $item->addtime);

                try {
                    $order->status = static::$STATUS_LIKETRY[$item->status];
                } catch (Exception $e) {
                    $order->status = 6;
                }


                $order->pay_status           = 1;
                $order->pay_id               = 0;
                $order->pay_name             = '';
                $order->bank                 = '';
                $order->goods_amount         = 0;
                $order->order_amount         = 0;
                $order->member_money         = 0;
                $order->reduce_amount        = 0;
                $order->coupon_id            = $item->e_no;
                $order->coupon_code          = '';
                $order->coupon_amount        = 0;
                $order->ship_amount          = '';
                $order->ship_amount_try_coin = 0;
                $order->is_invoice           = '';
                $order->remark               = $item->content;
                $order->update_time          = $item->modify_time;
                $order->try_coin             = $item->score;
                $order->source               = $item->origin;
                $order->create_time          = date('Y-m-d H:i:s', $item->addtime);


                if ($order->hasErrors()) {
                    static::info('导入order失败id:' . $item->no);
                }
                $order->save();


                $od                = new OrderGoods();
                $od->order_info_id = $order->order_info_id;
                $od->goods_id      = $item->product_no + static::$ILIKETRY_ID_BASE;
                $od->product_id    = $item->spec_no + static::$ILIKETRY_ID_BASE;
                $od->bestry_uid    = $bestry_uid;
                $od->buy_number    = 1;
                $od->buy_price     = 0;
                $od->create_time   = date('Y-m-d H:i:s', $item->addtime);
                $od->free_gift     = 0;
                $od->commented     = 0;
                $od->activity_id   = 0;
                $od->price_type    = 1;
                $od->try_coin      = $item->score;
                $od->save();
                if ($od->hasErrors()) {
                    static::info('导入goods失败id:' . $item->no . ' ' . ArrayHelper::arrayToString($od->getFirstErrors()));

                }


                $express                = new OrderExpress();
                $express->order_info_id = $order->order_info_id;
                $express->consignee     = mb_substr($item->member_name, 0, 20, 'utf-8');
                $express->address       = mb_substr($item->adress, 0, 80, 'utf-8');
                $express->delivery_code = '';
                $express->zip           = $item->code;


                try {
                    $express->province = static::$province[static::$city_province[$item->city_no]];
                } catch (Exception $e) {
                    $express->province = '';
                }

                try {
                    $express->city = static::$city[$item->city_no];
                } catch (Exception $e) {
                    $express->city = '';
                }
                try {
                    $express->county = static::$area[$item->area_no];
                } catch (Exception $e) {
                    $express->county = '';
                }


                $express->telephone     = $item->call;
                $express->mobile_phone  = $item->cell;
                $express->delivery_id   = 0;
                $express->delivery_time = 1;

                $express->create_time = date('Y-m-d H:i:s', $item->addtime);
                $express->save();


                unset($od, $order, $express);
            } catch (Exception $e) {
                static::info('导入express失败id:' . $item->no . ' ' . $e->getMessage());
            }
        }
        unset($result);
    }

    public function run()
    {
        static::info('开始导入从iliketry.order');
        if ($this->begin_id === 0) {
            $max_id = (int)OrderInfo::find()->where("order_info_id > " . LiketryToDTry::$ILIKETRY_ID_BASE . " and order_info_id < " . LiketryToDTry::$D_TRY_ID_BASE)->max('order_info_id');
            $max_id -= LiketryToDTry::$ILIKETRY_ID_BASE;
            $this->begin_id = $max_id ? $max_id : 0;
        }

        for ($times = 0; $times < LiketryToDTry::$ILIKETRY_ID_BASE; $times++) {
            $this->writeData();
            if ($this->isEnd) {
                break;
            }
        }
        static::info('结束导入.');
    }

    /**
     * @param Order $item
     */
    private function addCart(&$item)
    {

        try {
            $cart              = new Cart();
            $cart->number      = 1;
            $cart->goods_id    = $item->product_no + static::$ILIKETRY_ID_BASE;
            $cart->product_id  = $item->spec_no + static::$ILIKETRY_ID_BASE;
            $cart->bestry_uid  = static::$uids[$item->member_no];
            $cart->create_time = date('Y-m-d H:i:s', $item->addtime);
            $cart->update_time = date('Y-m-d H:i:s');
            $cart->save();
            if ($cart->hasErrors()) {
                static::info('购物车出错:' . $item->no . ' ' . ArrayHelper::arrayToString($cart->getFirstErrors()));
            }
            unset($cart);
        } catch (Exception $e) {
            static::info('购物车出错:' . $item->no . ' ' . $e->getMessage());
        }
    }

}